package com.clear.subject.domain.handler.subject;

import com.alibaba.fastjson.JSON;
import com.clear.subject.common.enums.IsDeletedFlagEnum;
import com.clear.subject.common.enums.SubjectInfoTypeEnum;
import com.clear.subject.domain.convert.SubjectBriefConverter;
import com.clear.subject.domain.convert.SubjectJudgeConverter;
import com.clear.subject.domain.entity.SubjectAnswerBO;
import com.clear.subject.domain.entity.SubjectInfoBO;
import com.clear.subject.domain.entity.SubjectOptionBO;
import com.clear.subject.infra.basic.entity.SubjectJudge;
import com.clear.subject.infra.basic.service.SubjectJudgeService;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 判断题目的策略类
 */
@Component
@Slf4j
public class JudgeTypeHandler implements SubjectTypeHandler {

    @Resource
    private SubjectJudgeService subjectJudgeService;

    /**
     * 枚举身份的识别
     *
     * @return
     */
    @Override
    public SubjectInfoTypeEnum getHandlerType() {
        return SubjectInfoTypeEnum.JUDGE;
    }

    /**
     * 实际的题目的插入
     *
     * @param subjectInfoBO
     */
    @Override
    public void add(SubjectInfoBO subjectInfoBO) {
        // ====判断题目的插入=====
        try {
            if (log.isInfoEnabled()) {
                log.info("JudgeTypeHandler.add.bo:{}", JSON.toJSONString(subjectInfoBO));
            }
            Preconditions.checkArgument(!CollectionUtils.isEmpty(subjectInfoBO.getOptionList()), "题目选项不能为空");

            SubjectJudge subjectJudge = new SubjectJudge();
            // 注意：判断题的选项只有一个：要么是对，要么是错
            // 因此不用像插入单选题一样for循环遍历所有选项
            SubjectAnswerBO subjectAnswerBO = subjectInfoBO.getOptionList().get(0);

            subjectJudge.setSubjectId(subjectInfoBO.getId());
            subjectJudge.setIsCorrect(subjectAnswerBO.getIsCorrect());
            subjectJudge.setIsDeleted(IsDeletedFlagEnum.UN_DELETE.getCode());

            subjectJudgeService.insert(subjectJudge);
        } catch (Exception e) {
            log.error("JudgeTypeHandler.add.error:{}", e.getMessage(), e);
        }
    }

    /**
     * 查询题目详情
     *
     * @param subjectId 题目id
     */
    @Override
    public SubjectOptionBO query(int subjectId) {
        SubjectJudge subjectJudge = new SubjectJudge();
        subjectJudge.setSubjectId(Long.valueOf(subjectId));

        // 根据题目id去查
        List<SubjectJudge> result = subjectJudgeService.queryByCondition(subjectJudge);

        List<SubjectAnswerBO> subjectAnswerBOList = SubjectJudgeConverter.INSTANCE.convertEntityToBoList(result);

        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        subjectOptionBO.setOptionList(subjectAnswerBOList);

        return subjectOptionBO;
    }
}
